<?php
/**
 * Created by PhpStorm.
 * User: dt
 * Time: 16:33
 */
namespace backend\models;

use Yii;
use yii\web\IdentityInterface;
use backend\base\BaseModel;


/**
 * 后台用户
 * @package app\models
 */
class AdminModel extends BaseModel implements IdentityInterface{
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'admin';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id','sex','age','create_time','parent_id', 'status','creator_id','role_id','emergency_tel','account_type','organization_id'], 'integer','message'=>'{attribute}必须是整数'],
            [['username','job_number','name','famous','number','emergency_relation','emergency_name'], 'string', 'max' => 40],
            [['password','native_place','card_address','address','email'], 'string', 'max' => 100],
            [['image'], 'string', 'max' => 200],
            [['mobile'], 'string', 'max' => 20],
            [['email'],'match', 'on' => ['add','edit'],'pattern'=>'/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/','message'=>'邮箱账号错误！'],
            //登录场景
            [['password'], 'required', 'on' => ['login'], 'message' => '{attribute}不能为空'],
            [['password'], 'required', 'on' => ['check_pwd'], 'message' => '{attribute}不能为空'],
            [['password'],'required', 'on'=> ['add'], 'message' => '{attribute}不能为空'],
            [['role_id'], 'required', 'on' => ['edit'], 'message' => '{attribute}不能为空'],
            [['id'], 'required', 'on' => ['login-id'], 'message' => '{attribute}不能为空']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id'=>'后台用户ID',
            'username'=>'姓名拼音',
            'password'=>'密码',
            'name'=>'真实姓名',
            'number'=>'身份证号',
            'job_number'=>'用户工号',
            'mobile'=>'联系电话',
            'email'=>'邮箱',
            'household'=>'户籍类型',
            'political'=>'政治面貌',
            'famous'=>'民族',
            'sex'=>'性别',
            'age'=>'年龄',
            'marital'=>'婚姻状况',
            'native_place'=>'籍贯',
            'card_address'=>'身份证地址',
            'address'=>'现居住地',
            'image'=>'照片地址',
            'emergency_relation'=>'紧急联系人关系',
            'emergency_tel'=>'紧急联系人电话',
            'emergency_name'=>'紧急联系人姓名',
            'role_id'=>'角色',
            'parent_id'=>'上级id',
            'organization_id'=>'机构id',
            'account_type'=>'账户类型 1员工 2经销商 3机构 4代理商',
            'creator_id'=>'创建人',
            'status'=>'用户状态0第一次登陆 1 正常 2禁用 3删除',
            'create_time'=>'新增时间'
        ];
    }

    /*
     * 保存前
     * @param bool $insert
     * @return bool
     */
    public function beforeSave($insert)
    {
        if(parent::beforeSave($insert)){
            $time = time();
            if($this->isNewRecord){
                $this->create_time = $time;
                $this->status = 1;
                $this->password = Yii::$app->security->generatePasswordHash($this->password.$time);
                $this->creator_id = Yii::$app->user->identity->id;
            }
            $this->status = isset($this->status) ? $this->status : 1;
            return true;
        }
        return false;
    }

    /*
     * 登录
     * @param $username
     * @return static
     */
    public function loginValidate($secret=false)
    {
        if(!empty($this->id)){
            $admin = self::findIdentity($this->id);
        }else if(!empty($this->job_number)){
            $admin = self::findIdentityByJobnumber($this->job_number);
        }else if(!empty($this->name)){
            $admin = self::findIdentityByName($this->name);
        }
        if (empty($admin)) {
            return false;//用户不存在
        }else{
            if ($secret == -1) {
                return $admin;
            }
            if (!empty($this->password) && Yii::$app->security->validatePassword($this->password.$admin->create_time, $admin->password)) {//存在，验证密码，验证通过返回identity实例
                return $admin;
            }elseif(!empty($this->id)){
                return $admin;
            }
        }
        return false;
    }

    /*
     * 用户列表
     */
    public function getList($data)
    {
        $condition = "1";
        if(!empty($data['mobile'])){
            $condition .= " and mobile like '%".$data['mobile']."%'";
        }
        if(!empty($data['username'])){
            $condition .= " and username like '%".$data['username']."%'";
        }
        $result = self::find()->where($condition);
        if(!empty($data['page'])){
            $num = ($data['page']-1)*15;
            $result->offset($num);
        }
        $res = $result->limit(15);
        $return['data'] = $res->asArray()->all();
        $return['count'] = $res->count();
        return $return;
    }

/*<<<<<<<<<<<<<以下是继承yii2登录校验时候默认要重写的一些方法不能删除>>>>>>>>>>>>>>>>>*/

    /**
     * 根据ID返回identity实例
     * @param int|string $id
     * @return static
     */
    public static function findIdentity($id)
    {
        $tmpIdentity   = static::findOne(['id' => $id]);
        return $tmpIdentity;
    }
    /**
     * 根据工号返回identity实例
     * @param $job_number
     * @return static
     */
    public static function findIdentityByJobnumber($job_number)
    {
        return static::findOne(['job_number' => $job_number]);
    }
    /**
     * 根据名称返回identity实例
     * @param $name
     * @return static
     */
    public static function findIdentityByName($name)
    {
        return static::findOne(['name' => $name]);
    }


    /**
     * 根据用户名返回identity实例
     * @param $username
     * @return static
     */
    public static function findIdentityByUsername($username)
    {
        return static::findOne(['mobile' => $username]);
    }

    /**
     * 根据access_token返回identity实例
     * @param mixed $token
     * @param null $type
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        // TODO: Implement findIdentityByAccessToken() method.
    }

    /**
     * 返回ID
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * cookie记住我 - 返回cookie中auth_key
     * @return mixed
     */
    public function getAuthKey()
    {
        //return $this->auth_key;
    }

    /**
     * cookie记住我 - 验证
     * @param string $authKey
     * @return bool
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['mobile' => $username]);
    }

    /**
     * Finds user by password reset token
     *
     * @param string $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token,
            'status' => self::STATUS_ACTIVE,
        ]);
    }

    /**
     * Finds out if password reset token is valid
     *
     * @param string $token password reset token
     * @return boolean
     */
    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int) substr($token, strrpos($token, '_') + 1);
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        return $timestamp + $expire >= time();
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password);
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
    }
    
}
